<script setup lang="ts">
/**
 *  权限分组组件，接受权限数据，根据对应菜单进行分组展示。使用了@element-plus:2.8.8。
 *  @Author 游王子og
 *  @Date 2025/02/13
 *  @Version 1.0.0
 *
 *  prop:
 *    permissionList: Permission[] = []: 权限数据
 *    echoPermissions: number[] = []: 回显选中的权限
 *  emit:
 *    update:permissions: (selectedPermissions: Permission[]) => void: 更新选中的权限触发事件
 */
//
import { computed, ref } from 'vue'
import type {Permission} from "@/components/interface/system/permission";

const props = defineProps<{
  permissionList: Permission[], // 权限数据
  echoPermissions: number[], // 回显选中的权限
}>()

// 定义事件，更新选中权限触发事件
const emits = defineEmits(['update:permissions'])

// 定义选中的权限
const selectedPermissions = ref(props.echoPermissions)

// 定义权限根据菜单分组展示
const permissionGroupByMenu = computed(() => {
  let map: any = {}
  let arr = props.permissionList
  for (let i = 0; i < arr.length; i++) {
    let ai = arr[i]
    if (!map[ai.menuNames]) {
      map[ai.menuNames] = [ai]
    } else {
      map[ai.menuNames].push(ai)
    }
  }
  let res: any = []
  Object.keys(map).forEach(key => {
    res.push({
      id: key.replace(',', ' - '),
      data: map[key]
    })
  })
  // 根据id排序
  res.sort((a: any, b: any) => {
    return a.id.localeCompare(b.id)
  })
  return res
})

</script>

<template>
  <div class="permission-group">
    <div style="margin-bottom: 10px" v-for="permissionGroup in permissionGroupByMenu">
      <label class="group-name">{{ permissionGroup.id }}：</label>
      <el-checkbox-group v-model="selectedPermissions">
        <el-checkbox-button
          @change="emits('update:permissions', selectedPermissions)"
          style="margin: 1px"
          v-for="permission in permissionGroup.data"
          :key="permission.id"
          :value="permission.id"
        >
          {{ permission.permissionDesc }}
        </el-checkbox-button>
      </el-checkbox-group>
    </div>
  </div>
</template>

<style scoped>
.permission-group {
  height: 360px;
  overflow-y: scroll;
}

.group-name {
  font-size: 16px;
  font-weight: bold;
}
</style>
